<script setup lang="ts">
defineOptions({
  name: "mainProgressStatus"
});
import { ref, reactive, onMounted, computed, markRaw, provide, watch } from "vue";
import ICON from "@/assets/svg/common/echarts.svg?component";
import mainProgressStatusItem from "./mainProgressStatusItem.vue";
import { useInitLoading } from "@/hooks/useCommon";
import { loadingTimeout } from "@/utils/http/constant";
import { ArrowLeft, ArrowRight } from "@px-ui/icons-vue";

interface Props {
  data?: Array<any> | null;
  dark?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  data: () => [],
  dark: false
});
const carouselContainer = ref(Math.random().toString(36).slice(2, 10));
const canPrev = ref(false);
const canNext = ref(true);
const pageList = ref([]);
const handelPrev = () => {
  carouselContainer.value.prev();
};
const handelNext = () => {
  carouselContainer.value.next();
};
const handleCarouse = index => {
  console.log(index);
  canPrev.value = index > 0;
  canNext.value = index < pageList.value.length - 1;
};
const checkEllipseFlag = (value, unit) => {
  if (value) {
    let len = 0;
    if (unit) {
      len = parseInt(value?.toString().length) + parseInt(unit?.toString().length);
    } else {
      len = parseInt(value?.toString().length);
    }
    if (len > 10) {
      return true;
    } else {
      return false;
    }
  } else {
    return false;
  }
};

const totalData = computed(() => {
  return props.data.map(item => {
    const {
      mainName = "",
      mainKey = "",
      power = 0,
      powerUnit = "",
      current = 0,
      currentUnit = "",
      voltage = 0,
      voltageUnit = "",
      voltageSpecMin = 0,
      voltageSpecMax = 0,
      currentSpecMin = 0,
      currentSpecMax = 0,
      frequency = 0,
      frequencyUnit = "",
      status = "",
      statusName = "",
      temperature = 0,
      temperatureName = "",
      temperatureUnit = "",
      ellipseFlag = false
    } = item;
    // const { min, max, colorIndex1, colorIndex2 } = calcVoltageQuota(voltageSpecMin, voltageSpecMax);
    const { min, max, colorIndex1, colorIndex2 } = calcCurrentQuota(currentSpecMin, currentSpecMax);
    const label = mainName;
    const text = `${current}${currentUnit}`;
    const subtext = mainName;
    const data = [{ value: current }];
    const echartsData = {
      text,
      subtext,
      colorIndex1,
      colorIndex2,
      voltageSpecMin,
      voltageSpecMax,
      currentSpecMin,
      currentSpecMax,
      min,
      max,
      data,
      currentUnit
    };
    const d1 = {
      label: "总功率",
      icon: markRaw(ICON),
      value: power,
      unit: powerUnit,
      type: "power",
      mainName,
      mainKey,
      ellipseFlag: checkEllipseFlag(power, powerUnit)
    };
    const d2 = {
      label: "频率",
      icon: markRaw(ICON),
      value: frequency,
      unit: frequencyUnit,
      type: "frequency",
      mainName,
      mainKey,
      ellipseFlag: checkEllipseFlag(frequency, frequencyUnit)
    };
    const d3 = {
      label: "电流",
      icon: markRaw(ICON),
      value: current,
      unit: currentUnit,
      type: "current",
      mainName,
      mainKey,
      ellipseFlag: checkEllipseFlag(current, currentUnit)
    };
    const d4 = {
      label: "电压",
      icon: markRaw(ICON),
      value: voltage,
      unit: voltageUnit,
      type: "voltage",
      mainName,
      mainKey,
      ellipseFlag: checkEllipseFlag(voltage, voltageUnit)
    };
    const d5 = {
      label: "状态",
      icon: null,
      value: statusName,
      unit: null,
      type: "statusName",
      mainName,
      mainKey,
      ellipseFlag: checkEllipseFlag(statusName, null)
    };
    const d6 = {
      label: "温度",
      icon: null,
      value: temperature,
      unit: temperatureUnit,
      type: "temperatureName",
      mainName,
      mainKey,
      ellipseFlag: checkEllipseFlag(temperature, null)
    };
    const listData = [d1, d2, d3, d4, d5, d6];
    return { label, echartsData, listData };
  });
});
watch(
  () => totalData,
  (newVal, oldVal) => {
    console.log("值已更新:", newVal);
    let newDataList = [];
    let current = 0;
    if (newVal.value && newVal.value.length > 0) {
      for (let i = 0; i < newVal.value.length; i++) {
        if (i % 4 !== 0 || i === 0) {
          if (!newDataList[current]) {
            newDataList.push([newVal.value[i]]);
          } else {
            newDataList[current].push(newVal.value[i]);
          }
        } else {
          current++;
          newDataList.push([newVal.value[i]]);
        }
      }
    }
    pageList.value = [...newDataList];
    if (pageList.value.length > 1) {
      canNext.value = true;
    }
  },
  {
    immediate: true,
    deep: true
  }
);

const mainProgressStatusClass = ref<string>(`mainProgressStatus_${Math.random().toString(36).slice(2, 10)}`);
const loadingInstance = ref<any>(null);
const mainProgressStatusItemRef = ref<any>(null);

const calcVoltageQuota = (voltageSpecMin: number, voltageSpecMax: number) => {
  let colorIndex1 = 0.2;
  let colorIndex2 = 0.8;
  const min = Math.round((voltageSpecMin * colorIndex2 - voltageSpecMax * colorIndex1) / (colorIndex2 - colorIndex1));
  const max = Math.round((voltageSpecMax - voltageSpecMin) / (colorIndex2 - colorIndex1)) + min;
  colorIndex1 = (voltageSpecMin - min) / (max - min);
  colorIndex2 = (voltageSpecMax - min) / (max - min);
  return { min, max, colorIndex1, colorIndex2 };
};

const calcCurrentQuota = (currentSpecMin: number, currentSpecMax: number) => {
  let colorIndex1 = 0.2;
  let colorIndex2 = 0.8;
  const min = Math.round((currentSpecMin * colorIndex2 - currentSpecMax * colorIndex1) / (colorIndex2 - colorIndex1));
  const max = Math.round((currentSpecMax - currentSpecMin) / (colorIndex2 - colorIndex1)) + min;
  colorIndex1 = (currentSpecMin - min) / (max - min);
  colorIndex2 = (currentSpecMax - min) / (max - min);
  return { min, max, colorIndex1, colorIndex2 };
};

const initLoading = () => {
  const target = `.${mainProgressStatusClass.value}`;
  loadingInstance.value = useInitLoading(target);
  setTimeout(() => {
    loadingInstance.value.close();
  }, loadingTimeout);
  return loadingInstance.value;
};

const updateEchartsOption = () => {
  for (const item of mainProgressStatusItemRef.value) {
    item.updateOption();
  }
};

defineExpose({
  loadingInstance,
  initLoading,
  updateEchartsOption
});
</script>

<template>
  <div class="main-progres-status-content" :class="mainProgressStatusClass">
    <div v-if="pageList.length > 1" class="arrowdiv">
      <px-button style="float: left" :icon="ArrowLeft" plain text :disabled="!canPrev" @click="handelPrev" />
      <px-button style="float: left" :icon="ArrowRight" plain text :disabled="!canNext" @click="handelNext" />
    </div>
    <px-carousel ref="carouselContainer" :loop="true" :autoplay="true" arrow="never" style="height: 100%" interval="5000" @change="handleCarouse">
      <px-carousel-item v-for="(list, index) in pageList" :key="index" class="main-progres-c-item">
        <div v-for="item in list" :key="item.label" class="content-item">
          <mainProgressStatusItem ref="mainProgressStatusItemRef" :data="item" :dark="dark" />
        </div>
        <template #arrow-left>
          <px-icon><ArrowLeft /></px-icon>
        </template>
      </px-carousel-item>
    </px-carousel>
  </div>
</template>

<style lang="scss" scoped>
.main-progres-status-content {
  width: 100%;
  height: 100%;

  .main-progres-c-item {
    display: flex;
    // gap: 10px;
    align-items: center;
    width: 100%;
    height: 100%;
  }

  .content-item {
    // flex: 1 0 25%;//calc(25% - 10px)
    // flex: 1;
    width: calc(25% - 8px);
    height: 100%;
    margin-right: 10px;

    &:last-child {
      margin-right: 0;
    }
  }
}

.arrowdiv {
  position: absolute;
  top: 10px;
  right: 0;
  z-index: 99999;
  width: 110px;
  height: 20px;

  i {
    cursor: pointer;
  }
}

:deep(.px-carousel__container) {
  position: relative;
  height: 100%;
}

:deep(.px-carousel__indicators--horizontal) {
  bottom: -15px;
}
</style>
